package com.qiji.video.config;

import com.qiji.video.bean.Users;
import com.qiji.video.exception.ServiceException;
import com.qiji.video.service.IUserService;
import com.qiji.video.util.JwtUtil;
import com.qiji.video.util.ResultCode;
import lombok.SneakyThrows;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;
import java.util.HashMap;
import java.util.concurrent.ConcurrentHashMap;

public class MyRealm extends AuthorizingRealm {


    @Autowired
    private IUserService userService;
    // 存储用户的jwt，用于登录成功后能获取到jwt
    private ConcurrentHashMap jwtMap = new ConcurrentHashMap();

    // 授权
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        System.out.println("授权");
        return null;
    }

    // 认证
    @SneakyThrows
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        UsernamePasswordToken token = (UsernamePasswordToken) authenticationToken;
        String username = token.getUsername();
        Users user = userService.userLogin(token.getUsername(),"");
        // 用户不存在
        if (user==null){
            throw new ServiceException(ResultCode.USER_NULL);
        }else {
            // 通过 设置jwt
            setJwt(user,token.getUsername());
            return new SimpleAuthenticationInfo(username,user.getPassword(),this.getName());
        }
    }

    // 登录成功后设置jwt
    public void setJwt(Users users,String username){
        HashMap map=new HashMap();
        map.put("role",users.getRole());
        jwtMap.put(username,JwtUtil.sign(users.getId().toString(),map));;
    }
    public String getJwt(String username){
        return (String) jwtMap.get(username);
    }
}
